package o.json;

import java.io.IOException;

/**
 * JSON Reader 2
 * @author per.a.engstrom
 *
 */
public class JSONReader2 extends JSONReader {
	public JSONReader2(String text) {
		super(text);
	}

	@Override
	public JSONValue readValue() throws JSONException {
		skipSpaces();

		return super.readValue();
	}

	@Override
	protected JSONObject readObject() throws JSONException {
		try {
			final JSONObject object = new JSONObject();

			reader.read(); // {
			for (int i = 0; true; ++i) {
				skipSpaces();

				if (testString("}")) {
					break;
				}

				if (i != 0) {
					if (testString(",")) {
						reader.read(); // ,
					} else {
						throw new JSONException("expected ','");
					}
				}

				skipSpaces();

				final JSONString key = readString();
				if (testString(":")) {
					reader.read(); // :
				} else {
					throw new JSONException("expected ':'");
				}

				final JSONValue value = readValue();
				object.setValue(key, value);
			}
			reader.read(); // }

			return object;
		} catch (IOException e) {
			e.printStackTrace();
		}
		throw new JSONException();
	}

	@Override
	protected JSONArray readArray() throws JSONException {
		try {
			final JSONArray array = new JSONArray();

			reader.read(); // [
			for (int i = 0; true; ++i) {
				if (testString("]")) {
					break;
				}

				skipSpaces();

				if (i != 0) {
					if (testString(",")) {
						reader.read();
					} else {
						throw new JSONException();
					}
				}

				skipSpaces();

				JSONValue value = readValue();
				array.addValue(value);
			}
			reader.read(); // ]

			return array;
		} catch (IOException e) {
			e.printStackTrace();
		}
		throw new JSONException();
	}

	private void skipSpaces() {
		try {
			boolean done = false;
			while (!done) {
				reader.mark(1);
				char[] data = new char[1];
				reader.read(data);

				if (data[0] == ' ') continue;
				if (data[0] == '\t') continue;
				if (data[0] == '\n') continue;

				reader.reset();
				done = true;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
